package com.lfy.yunpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfy.yunpicture.common.ErrorCode;
import com.lfy.yunpicture.constant.CommonConstant;
import com.lfy.yunpicture.exception.BusinessException;
import com.lfy.yunpicture.exception.ThrowUtils;
import com.lfy.yunpicture.manager.CosManager;
import com.lfy.yunpicture.manager.auth.SpaceUserAuthManager;
import com.lfy.yunpicture.mapper.PictureMapper;
import com.lfy.yunpicture.mapper.SpaceMapper;
import com.lfy.yunpicture.model.dto.space.SpaceAddRequest;
import com.lfy.yunpicture.model.dto.space.SpaceQueryRequest;
import com.lfy.yunpicture.model.entity.Picture;
import com.lfy.yunpicture.model.entity.Space;
import com.lfy.yunpicture.model.entity.SpaceUser;
import com.lfy.yunpicture.model.entity.User;
import com.lfy.yunpicture.model.enums.SpaceLeaveEnum;
import com.lfy.yunpicture.model.enums.SpaceRoleEnum;
import com.lfy.yunpicture.model.enums.SpaceTypeEnum;
import com.lfy.yunpicture.model.vo.SpaceVO;
import com.lfy.yunpicture.model.vo.UserVO;
import com.lfy.yunpicture.service.SpaceService;
import com.lfy.yunpicture.service.SpaceUserService;
import com.lfy.yunpicture.service.UserService;
import com.lfy.yunpicture.utils.SqlUtils;
import com.qcloud.cos.exception.CosClientException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 空间服务实现
 */
@Service
@Slf4j
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space> implements SpaceService {

    @Resource
    private UserService userService;
    @Resource
    private PictureMapper pictureMapper;
    @Resource
    private CosManager cosManager;
    @Resource
    @Lazy
    private SpaceUserAuthManager spaceUserAuthManager;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    @Lazy
    private SpaceUserService spaceUserService;
//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;

    /**
     * 校验数据
     *
     * @param space
     * @param add   对创建的数据进行校验
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(spaceName), ErrorCode.PARAMS_ERROR, "空间名字为空");
            ThrowUtils.throwIf(ObjectUtil.isEmpty(spaceLevel), ErrorCode.PARAMS_ERROR, "空间级别为空");
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (StringUtils.isNotBlank(spaceName)) {
            ThrowUtils.throwIf(spaceName.length() > 15, ErrorCode.PARAMS_ERROR, "空间名字过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Long userId = spaceQueryRequest.getUserId();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        Integer spaceType = spaceQueryRequest.getSpaceType();

        // 补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(spaceName), "spaceName", spaceName);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjectUtils.isNotEmpty(spaceType), "spaceType", spaceType);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取空间封装
     *
     * @param space
     * @param request
     * @return
     */
    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        // 对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);

        // region 可选
        // 1. 关联查询用户信息
        Long userId = space.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        spaceVO.setUser(userVO);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // endregion
        return spaceVO;
    }

    /**
     * 分页获取空间封装
     *
     * @param spacePage
     * @param request
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(space -> {
            return SpaceVO.objToVo(space);
        }).collect(Collectors.toList());

        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        // endregion

        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSpace(Long id, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        // 判断是否存在
        Space oldSpace = this.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldSpace.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 删除空间表
        boolean result = this.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 删除空间用户表
        if (oldSpace.getSpaceType().equals(SpaceTypeEnum.TEAM.getValue())) {
            boolean remove = spaceUserService.lambdaUpdate()
                    .eq(SpaceUser::getSpaceId, id)
                    .remove();
            ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR);
        }
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<Picture>()
                .eq("spaceId", id);
        List<Picture> pictures = pictureMapper.selectList(queryWrapper);
        // 需要删除空间中的所有照片
        try {
            pictureMapper.delete(queryWrapper);
        } catch (RuntimeException e) {
            log.error("删除空间中的照片失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        // 删除cos容器中的照片
        for (Picture picture : pictures) {
            String thumbnail = picture.getThumbnail();
            String url = picture.getUrl();
            try {
                cosManager.deleteObject(url, thumbnail);
            } catch (CosClientException e) {
                log.error("cos file delete error", e);
            }
        }
        return true;
    }

    @Override
    public Long addSpace(SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        Integer spaceType = spaceAddRequest.getSpaceType();
        ThrowUtils.throwIf(spaceType != null && !SpaceTypeEnum.getValues().contains(spaceType), ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 添加默认值
        if (spaceType == null) {
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 根据空间级别获取枚举值
        SpaceLeaveEnum enumBySpaceLeave = SpaceLeaveEnum.getEnumBySpaceLeave(spaceAddRequest.getSpaceLevel());
        ThrowUtils.throwIf(enumBySpaceLeave == null, ErrorCode.PARAMS_ERROR, "不存在该级别的空间");
        // 如果不是管理员，那么只能创建普通空间
        if (!userService.isAdmin(request)) {
            ThrowUtils.throwIf(enumBySpaceLeave != SpaceLeaveEnum.COMMON, ErrorCode.NO_AUTH_ERROR, "非管理员不能创建非普通空间");
        }
        space.setMaxSize(enumBySpaceLeave.getMaxSize());
        space.setMaxCount(enumBySpaceLeave.getMaxCount());
        // 数据校验
        this.validSpace(space, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        // 将每个用户ID作为一把锁
        String lock = String.valueOf(userId).intern();
        final long[] newSpaceId = {0};
        transactionTemplate.execute((status) -> {
            synchronized (lock) {
                // 每个用户只能创建一个私有空间或者团队空间，需查询数据库
                boolean exists = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .eq(Space::getSpaceType, space.getSpaceType())
                        .exists();
                ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每个用户只能创建一个空间");
                // 写入数据库
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                // 如果是创建团队空间，那么自动向团队空间成员表添加当前用户
                if (Objects.equals(space.getSpaceType(), SpaceTypeEnum.TEAM.getValue())) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    boolean addTeamMember = spaceUserService.save(spaceUser);
                    ThrowUtils.throwIf(!addTeamMember, ErrorCode.OPERATION_ERROR);
                }
                // 返回新写入的数据 id
                newSpaceId[0] = space.getId();
                return newSpaceId[0];
            }
        });
//        // 动态创建数据库表
//        dynamicShardingManager.createTable(space);
        return newSpaceId[0];
    }

    @Override
    public List<SpaceVO> listMySpaceVO(User loginUser) {
        // 查询该用户加入的团队空间列表
        Set<Long> spaceIdSet = spaceUserService.lambdaQuery()
                .eq(SpaceUser::getUserId, loginUser.getId())
                .list()
                .stream()
                .map(SpaceUser::getSpaceId)
                .collect(Collectors.toSet());
        List<SpaceVO> spaceVOList = this.lambdaQuery()
                .in(CollUtil.isNotEmpty(spaceIdSet), Space::getId, spaceIdSet)
                .or(CollUtil.isNotEmpty(spaceIdSet))
                .eq(Space::getUserId, loginUser.getId())
                .list()
                .stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());
        return spaceVOList;
    }
}
